package com.jjsj.mall.shop.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jjsj.mall.entity.*;
import com.jjsj.mall.service.*;
import com.jjsj.mall.shop.entity.*;
import com.jjsj.mall.shop.mapper.YoshopUserMapper;
import com.jjsj.mall.shop.service.*;
import com.jjsj.weixin.entity.WxUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * jjsj用户Service业务层处理
 *
 * @author www.joolun.com
 * @date 2022-10-24
 */
@Service
public class YoshopUserServiceImpl implements IYoshopUserService {
    @Autowired
    private YoshopUserMapper yoshopUserMapper;

    @Autowired
    private IYoshopUserAddressService userAddressService;

    @Autowired
    private IYoshopUserReceipteService userReceipteService;

    @Autowired
    private JJSJUserService jjsjUserService;

    @Autowired
    private IYoshopOrderService orderService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private GoodsSpuService goodsSpuService;

    @Autowired
    private OrderLogisticsService orderLogisticsService;


    @Autowired
    private IOrderReceiptService orderReceiptService;

    @Autowired
    private OrderItemService orderItemService;


    List<OrderItem> list1 = new ArrayList<>();

    /**
     * 查询jjsj用户
     *
     * @param userId jjsj用户ID
     * @return jjsj用户
     */
    @Override
    public YoshopUser selectYoshopUserById(String userId) {
        return yoshopUserMapper.selectYoshopUserById(userId);
    }

    /**
     * 查询jjsj用户列表
     *
     * @param yoshopUser jjsj用户
     * @return jjsj用户
     */
    @Override
    public List<YoshopUser> selectYoshopUserList(YoshopUser yoshopUser) {
        List<YoshopUser> list = yoshopUserMapper.selectYoshopUserList(yoshopUser);
        this.processData(list);
        return list;
    }

    /**
     * 新增jjsj用户
     *
     * @param yoshopUser jjsj用户
     * @return 结果
     */
    @Override
    public int insertYoshopUser(YoshopUser yoshopUser) {
        return yoshopUserMapper.insertYoshopUser(yoshopUser);
    }

    /**
     * 修改jjsj用户
     *
     * @param yoshopUser jjsj用户
     * @return 结果
     */
    @Override
    public int updateYoshopUser(YoshopUser yoshopUser) {
        return yoshopUserMapper.updateYoshopUser(yoshopUser);
    }

    /**
     * 批量删除jjsj用户
     *
     * @param userIds 需要删除的jjsj用户ID
     * @return 结果
     */
    @Override
    public int deleteYoshopUserByIds(String[] userIds) {
        return yoshopUserMapper.deleteYoshopUserByIds(userIds);
    }

    /**
     * 删除jjsj用户信息
     *
     * @param userId jjsj用户ID
     * @return 结果
     */
    @Override
    public int deleteYoshopUserById(String userId) {
        return yoshopUserMapper.deleteYoshopUserById(userId);
    }


    @Async
    void processData(List<YoshopUser> list) {
        Map<String, String> map = new HashMap<>();
        map.put("10004", "1584464554769186817");
        map.put("10005", "1366616360643538946");
        map.put("10006", "1584463989955821569");
        map.put("10007", "1578626274093879298");
        for (YoshopUser user : list) {
            WxUser wxUser = null;
            wxUser = jjsjUserService.selectUserByOpenId(user.getOpenId());
            if (wxUser == null || wxUser.getId() == null) {
                wxUser = new WxUser();
                wxUser.setOpenId(user.getOpenId());
                wxUser.setNickName(user.getNickname());
                wxUser.setHeadimgUrl(user.getAvatarurl());
                wxUser.setProvince(user.getProvince());
                wxUser.setCity(user.getCity());
                wxUser.setCountry(user.getCountry());
                wxUser.setSex(user.getGender());
                wxUser.setCreateTime(LocalDateTime.ofEpochSecond(user.getCreateTime(), 0, ZoneOffset.ofHours(8)));
                wxUser.setUpdateTime(LocalDateTime.ofEpochSecond(user.getUpdateTime(), 0, ZoneOffset.ofHours(8)));
                wxUser.setAppType("1");
                jjsjUserService.create(wxUser);
            }
            if (wxUser != null && wxUser.getId() != null) {
                YoshopUserAddress yoshopUserAddress = new YoshopUserAddress();
                yoshopUserAddress.setUserId(user.getUserId());
                List<YoshopUserAddress> addressList = userAddressService.selectYoshopUserAddressList(yoshopUserAddress);
                for (YoshopUserAddress address : addressList) {
                    UserAddress userAddress = new UserAddress();
                    if (user.getAddressId().equals(address.getAddressId())) {
                        userAddress.setIsDefault("1");
                    } else {
                        userAddress.setIsDefault("0");
                    }
                    userAddress.setUserId(wxUser.getId());
                    userAddress.setCreateTime(LocalDateTime.now());
                    userAddress.setUpdateTime(LocalDateTime.now());
                    userAddress.setUserName(address.getName());
                    userAddress.setTelNum(address.getPhone());
                    userAddress.setProvinceName(address.getProvince());
                    userAddress.setCityName(address.getCity());
                    userAddress.setCountyName(address.getRegion());
                    userAddress.setDetailInfo(address.getDetail());
                    jjsjUserService.createAddress(userAddress);
                }
                YoshopUserReceipte yoshopUserReceipte = new YoshopUserReceipte();
                yoshopUserReceipte.setUserId(user.getUserId());
                List<YoshopUserReceipte> receipteList = userReceipteService.selectYoshopUserReceipteList(yoshopUserReceipte);
                for (YoshopUserReceipte receipte : receipteList) {
                    UserReceipt userReceipt = new UserReceipt();
                    if (user.getReceipteId().equals(receipte.getReceipteId())) {
                        userReceipt.setIsDefault("1");
                    } else {
                        userReceipt.setIsDefault("0");
                    }
                    userReceipt.setUserId(wxUser.getId());
                    userReceipt.setCreateTime(LocalDateTime.now());
                    userReceipt.setUpdateTime(LocalDateTime.now());
                    userReceipt.setReceiptTitle(receipte.getReceipteTitle());
                    userReceipt.setReceiptType(receipte.getReceipteType());
                    userReceipt.setAccountBank(receipte.getAccountBank());
                    userReceipt.setAccountCode(receipte.getAccountCode());
                    userReceipt.setAddress(receipte.getAddress());
                    userReceipt.setDelFlag("0");
                    userReceipt.setTaxpayerId(receipte.getTaxpayerId());
                    userReceipt.setRemark(receipte.getRemark());
                    userReceipt.setTelephone(receipte.getTelephone());
                    jjsjUserService.createReceipt(userReceipt);
                }
                YoshopOrder yoshopOrder = new YoshopOrder();
                yoshopOrder.setUserId(user.getUserId());
                List<YoshopOrder> orderList = orderService.selectYoshopOrderList(yoshopOrder);
                for (YoshopOrder order : orderList) {
                    List<YoshopOrderGoods> goodsList = order.getGoodsList();
                    boolean isExist = true;
                    if (goodsList.isEmpty()) {
                        isExist = false;
                    }
                    for (YoshopOrderGoods goods : goodsList) {
                        String goodsId = goods.getGoodsId();
                        if (!map.containsKey(goodsId)) {
                            isExist = false;
                            break;
                        }
                    }
                    if (isExist) {
                        OrderInfo orderInfo = new OrderInfo();
                        String status = null;
                        if (order.getPayStatus().equals("10")) {
                            orderInfo.setIsPay("0");
//                            status = "0";
                        } else if (order.getPayStatus().equals("20")) {
                            orderInfo.setIsPay("1");
                            if (order.getDeliveryStatus().equals("10")) {
                                status = "1";
                            } else if (order.getDeliveryStatus().equals("20")) {
                                status = "2";
                                if (order.getReceiptStatus().equals("20")) {
                                    status = "3";
                                }
                            } else {
                                status = "4";
                            }
                        }
                        orderInfo.setStatus(status);
                        new Date(System.currentTimeMillis());
                        orderInfo.setCreateTime(order.getCreateTime().equals("0") ? null : LocalDateTime.ofEpochSecond(order.getCreateTime(), 0, ZoneOffset.ofHours(8)));
                        orderInfo.setUpdateTime(order.getUpdateTime().equals("0") ? null : LocalDateTime.ofEpochSecond(order.getUpdateTime(), 0, ZoneOffset.ofHours(8)));
                        orderInfo.setPaymentTime(order.getPayTime().equals("0") ? null : LocalDateTime.ofEpochSecond(Long.parseLong(order.getPayTime()), 0, ZoneOffset.ofHours(8)));
                        orderInfo.setDeliveryTime(order.getDeliveryTime().equals("0") ? null : LocalDateTime.ofEpochSecond(Long.parseLong(order.getDeliveryTime()), 0, ZoneOffset.ofHours(8)));
                        orderInfo.setReceiverTime(order.getReceiptTime().equals("0") ? null : LocalDateTime.ofEpochSecond(Long.parseLong(order.getReceiptTime()), 0, ZoneOffset.ofHours(8)));
                        orderInfo.setClosingTime(order.getUpdateTime().equals("0") ? null : LocalDateTime.ofEpochSecond(order.getUpdateTime(), 0, ZoneOffset.ofHours(8)));
                        orderInfo.setPaymentWay("2");
                        orderInfo.setFreightPrice(new BigDecimal("0"));
                        orderInfo.setSalesPrice(order.getTotalPrice());
                        orderInfo.setPaymentPrice(order.getPayPrice());
                        orderInfo.setTransactionId(order.getTransactionId());
                        orderInfo.setIsSelf(order.getIsSelf() == null ? "0" : order.getIsSelf().equals("是") ? "1" : "0");
                        orderInfo.setOrderNo(order.getOrderNo());
                        orderInfo.setUserId(wxUser.getId());
                        orderInfo.setDelFlag("0");
                        orderInfoService.save(orderInfo);
                        if (orderInfo.getId() != null) {
                            List<OrderItem> listOrderItem = new ArrayList<>();
                            List<GoodsSpu> listGoodsSpu = new ArrayList<>();
                            for (YoshopOrderGoods goods : goodsList) {
                                String goodsId = goods.getGoodsId();
                                if (map.containsKey(goodsId)) {
                                    String id = map.get(goodsId);
                                    GoodsSpu goodsSpu = goodsSpuService.getOne(Wrappers.<GoodsSpu>lambdaQuery()
                                            .eq(GoodsSpu::getId, id));
                                    if (goodsSpu != null) {
                                        OrderItem orderItem = new OrderItem();
                                        orderItem.setOrderId(orderInfo.getId());
                                        orderItem.setSpuId(goodsSpu.getId());
                                        orderItem.setSpuName(goodsSpu.getName());
                                        orderItem.setPicUrl(goodsSpu.getPicUrls()[0].replace("localhost", "192.168.31.81"));
                                        orderItem.setQuantity(Integer.parseInt(goods.getTotalNum()));
                                        orderItem.setSalesPrice(goodsSpu.getSalesPrice());
                                        orderItem.setFreightPrice(BigDecimal.ZERO);
                                        orderItem.setPaymentPrice(goods.getTotalPrice());
                                        orderItem.setDelFlag("0");
                                        orderItem.setCreateTime(goods.getCreateTime().equals("0") ? null : LocalDateTime.ofEpochSecond(goods.getCreateTime(), 0, ZoneOffset.ofHours(8)));
                                        orderItem.setUpdateTime(goods.getCreateTime().equals("0") ? null : LocalDateTime.ofEpochSecond(goods.getCreateTime(), 0, ZoneOffset.ofHours(8)));
                                        listOrderItem.add(orderItem);
                                    }
                                }
                                if (listOrderItem.size() > 0) {
                                    if (orderInfo.getIsPay().equals("1")) {
                                        OrderLogistics orderLogistics = new OrderLogistics();
                                        YoshopOrderAddress address = order.getOrderAddress();
                                        if (address != null) {
                                            orderLogistics.setLogistics(order.getExpressCompany().contains("顺丰") ? "shunfeng" : "qita");
                                            orderLogistics.setLogisticsNo(order.getExpressNo());
                                            orderLogistics.setCreateTime(order.getDeliveryTime().equals("0") ? null : LocalDateTime.ofEpochSecond(Long.parseLong(order.getDeliveryTime()), 0, ZoneOffset.ofHours(8)));
                                            orderLogistics.setUpdateTime(order.getReceiptTime().equals("0") ? null : LocalDateTime.ofEpochSecond(Long.parseLong(order.getReceiptTime()), 0, ZoneOffset.ofHours(8)));
                                            orderLogistics.setUserName(address.getName());
                                            orderLogistics.setTelNum(address.getPhone());
                                            orderLogistics.setAddress(address.getProvince() + address.getCity() + address.getRegion() + address.getDetail());
                                        } else {
                                            orderLogistics.setUserName(wxUser.getNickName());
                                            orderLogistics.setTelNum(wxUser.getPhone() == null ? "0851-84844703" : wxUser.getPhone());
                                            orderLogistics.setAddress("自提");
                                            orderLogistics.setLogistics("qita");
                                            orderLogistics.setLogisticsNo("自提");
                                            orderLogistics.setCreateTime(order.getDeliveryTime().equals("0") ? null : LocalDateTime.ofEpochSecond(Long.parseLong(order.getDeliveryTime()), 0, ZoneOffset.ofHours(8)));
                                            orderLogistics.setUpdateTime(order.getReceiptTime().equals("0") ? null : LocalDateTime.ofEpochSecond(Long.parseLong(order.getReceiptTime()), 0, ZoneOffset.ofHours(8)));
                                        }
                                        //新增订单物流
                                        orderLogisticsService.save(orderLogistics);
                                        orderInfo.setLogisticsId(orderLogistics.getId());
                                    }
                                    OrderReceipt orderReceipt = new OrderReceipt();
                                    YoshopOrderReceipte receipte = order.getOrderReceipte();
                                    orderReceipt.setAccountCode(receipte.getAccountCode());
                                    orderReceipt.setAddress(receipte.getAddress());
                                    orderReceipt.setReceiptTitle(receipte.getReceipteTitle());
                                    orderReceipt.setAccountBank(receipte.getAccountBank());
                                    orderReceipt.setReceiptType(receipte.getReceipteType());
                                    orderReceipt.setTelephone(receipte.getTelephone());
                                    orderReceipt.setTaxpayerId(receipte.getTaxpayerId());
                                    orderReceiptService.save(orderReceipt);
                                    orderInfo.setReceiptId(orderReceipt.getId());
                                    orderInfo.setName(listOrderItem.get(0).getSpuName());
                                    orderInfoService.saveOrUpdate(orderInfo);//保存订单
                                    boolean isLoop = true;
                                    while (isLoop) {
                                        try {
                                            list1 = listOrderItem;
//                                                listOrderItem.forEach(orderItem -> {
//                                                    orderItem.setOrderId(orderInfo.getId());
//                                                    orderItemService.saveOrUpdate(orderItem);
//                                                    list1.remove(orderItem);
//                                                });
                                            for (int i = 0; i < listOrderItem.size(); i++) {
                                                OrderItem orderItem = listOrderItem.get(i);
                                                orderItem.setOrderId(orderInfo.getId());
                                                orderItemService.saveOrUpdate(orderItem);
                                                list1.remove(i);
                                            }
                                            if (list1.size() == 0) {
                                                isLoop = false;
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            listOrderItem = list1;
                                        }
                                    }
                                    //保存订单详情
//                                        orderItemService.saveBatch(listOrderItem);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}